package com.sense.cloud.coreservice.sdk.auth.filter;

import com.alibaba.fastjson.JSON;
import com.sense.cloud.coreservice.sdk.auth.annotation.CodeWithHandler;
import com.sense.cloud.coreservice.sdk.auth.modules.ChkResult;
import com.sense.cloud.coreservice.sdk.auth.modules.ErrorCode;
import com.sense.cloud.coreservice.sdk.auth.modules.UserAppService;
import com.sense.cloud.coreservice.sdk.auth.utils.StringUtils;
import com.sense.cloud.coreservice.sdk.auth.utils.http.assist.AuthConstants;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

public abstract class CodeAuthJaxrsFilter implements ContainerRequestFilter {
	private Logger log = LoggerFactory.getLogger(getClass());
	private UserAppService userAppService = new UserAppService();
	private String packages;

	public void setPackages(String packages) {
		this.packages = packages;
	}

	@Override
	public void filter(ContainerRequestContext request) throws IOException {

		UriInfo uriinfo = request.getUriInfo();
		String hosts = uriinfo.getBaseUri().toString();
		hosts = hosts.substring(0, hosts.length() - 1);
		// String action = uriinfo.getPath();
		String uri = uriinfo.getRequestUri().toString();

		// code check
		CodeWithHandler.getInstance().scanner(packages);
		int ssaccesskeyIndex = uri.indexOf(AuthConstants.ACCESSKEY);
		int ssnonceIndex = uri.indexOf(AuthConstants.NONCE);
		String ssaccesskey = uri.substring(ssaccesskeyIndex + AuthConstants.ACCESSKEY.length() + 1, ssnonceIndex - 1);

		String action = StringUtils.getAction(uri);
		boolean chkRes = CodeWithHandler.getInstance().checkUriCode(action, ssaccesskey);

		if (!chkRes) {
			ChkResult res = new ChkResult();
			res.setResult(false);
			res.setStatus(ErrorCode.ERROR_PERMISSIONS);
			String resStr = JSON.toJSONString(res);
			request.abortWith(Response.status(401).header("Content-Type", "application/json;charset=UTF-8")
					.entity(resStr).build());
			log.error("get " + resStr);
		}

		//
		String method = request.getMethod();
		if ("GET".equals(method)) {

			ChkResult res = userAppService.validateGet(uri);
			if (!res.isResult()) {
				String resStr = JSON.toJSONString(res);
				log.error("get " + resStr);
				request.abortWith(Response.status(401).header("Content-Type", "application/json;charset=UTF-8")
						.entity(resStr).build());
			}

		} else if ("POST".equals(method)) {
			InputStream input = request.getEntityStream();
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] bs = new byte[1024];
			int index = 0;

			if (input != null) {
				while ((index = input.read(bs)) > -1) {
					bos.write(bs, 0, index);
				}
			}

			byte[] b2 = bos.toByteArray();
			bos.flush();
			ByteArrayInputStream bis = new ByteArrayInputStream(b2);
			request.setEntityStream(bis);
			ChkResult res = userAppService.validatePost(uri, b2);
			if (!res.isResult()) {
				String resStr = JSON.toJSONString(res);
				log.error("post " + resStr);
				request.abortWith(Response.status(401).header("Content-Type", "application/json;charset=UTF-8")
						.entity(resStr).build());
			}
		}
	}

}
